import sys
sys.path.append("..")
from PyQt5.QtWidgets import QWidget, QLabel, QGridLayout, QApplication, \
     QFileDialog, QGraphicsDropShadowEffect, QPlainTextEdit
from PyQt5.QtGui import QPixmap, QFont, QCursor
from PyQt5.QtCore import Qt
from Dialog import FileDialog, WarningMessageBox
from base64 import b64encode, b64decode
from handler.leasedLandHandle import LeaseLandHandle
import requests
import sys
import time
import cv2
import numpy as np
import copy

import shutil
import os
from shopInterfaceTools import shopItem, EditWidget, slideShowWidget,\
    msgEditWidget, ItemDisplayWidget, picEditableLabel

landList = [{
        "land_id": "1",
        "land_title": "1号大棚",  # 标题
        "land_rules": "需要等待种植的种类成熟后方可寄出。", # 种植规则
        "imagesSlider": [
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3992045535,69144840&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3156874013,635811390&fm=26&gp=0.jpg"
        ], # 轮播图
        "defaultImgIndex": 0, # 默认图片索引（取轮播图）
        "land_stock": 27,  # 土地总块数
        "land_planted": 3,  # 土地已种植数
        "items":[  # 可选种植种类
            {
                "item_id": "1",
                "item_title": "菠菜",
                "item_cycle": 90,  # 生长周期
                "item_img": "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/"
                            "it/u=3637305469,1928156414&fm=26&gp=0.jpg",
                "item_price": 9.9,  # 价格
                "item_count": 5,  # 需达标数量
                "item_weight": 5, # 单份重量
                "item_introduce": "菠菜有“营养模范生”之称，它富含类胡萝卜素、维生素C、维生素K、矿物质（钙质、铁"
                                  "质等）、辅酶Q10等多种营养素。其可以经常用来烧汤，凉拌，单炒，和配荤菜合炒或垫盘。以色泽浓绿，根为红色，不着水，茎叶不老，无抽苔开花，不带黄烂叶者为佳"  # 描述
            },
            {
                "item_id": "1",
                "item_title": "空心菜",
                "item_cycle": 60,
                "item_img": "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3812919490,11103409"
                            "30&fm=26&gp=0.jpg",
                "item_price": 8.9,
                "item_count": 10,
                "item_weight": 5,
                "item_introduce": "空心菜是碱性食物，并含有钾、氯等调节水液平衡的元素，食后可降低肠道的酸度，预"
                                  "防肠道内的菌群失调，对防癌有益。所含的烟酸、维生素C等能降低胆固醇、甘油三酯，具有降脂减肥的功效。空心菜中的叶绿素有“绿色精灵”之称，可洁齿防龋除口臭，健美皮肤。",
            },
        ],
        "imageContent":["https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3637305469,1928156414&fm=26&gp=0.jpg",
                        "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
                        "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3812919490,1110340930&fm=26&gp=0.jpg"],  # 合种租地图片详情
        "videos": "",  # 存放视频地址
        "status": "0",  # 状态
    },
{
        "land_id": "1",
        "land_title": "1号大棚",  # 标题
        "land_rules": "需要等待种植的种类成熟后方可寄出。", # 种植规则
        "imagesSlider": [
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3156874013,635811390&fm=26&gp=0.jpg",
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3992045535,69144840&fm=26&gp=0.jpg",
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg"
        ], # 轮播图
        "defaultImgIndex": 0, # 默认图片索引（取轮播图）
        "land_stock": 27,  # 土地总块数
        "land_planted": 3,  # 土地已种植数
        "items":[  # 可选种植种类
            {
                "item_id": "1",
                "item_title": "菠菜",
                "item_cycle": 90,  # 生长周期
                "item_img": "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/"
                            "it/u=3637305469,1928156414&fm=26&gp=0.jpg",
                "item_price": 9.9,  # 价格
                "item_count": 5,  # 需达标数量
                "item_weight": 5, # 单份重量
                "item_introduce": "菠菜有“营养模范生”之称，它富含类胡萝卜素、维生素C、维生素K、矿物质（钙质、铁"
                                  "质等）、辅酶Q10等多种营养素。其可以经常用来烧汤，凉拌，单炒，和配荤菜合炒或垫盘。以色泽浓绿，根为红色，不着水，茎叶不老，无抽苔开花，不带黄烂叶者为佳"  # 描述
            },
            {
                "item_id": "1",
                "item_title": "空心菜",
                "item_cycle": 60,
                "item_img": "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3812919490,11103409"
                            "30&fm=26&gp=0.jpg",
                "item_price": 8.9,
                "item_count": 10,
                "item_weight": 5,
                "item_introduce": "空心菜是碱性食物，并含有钾、氯等调节水液平衡的元素，食后可降低肠道的酸度，预"
                                  "防肠道内的菌群失调，对防癌有益。所含的烟酸、维生素C等能降低胆固醇、甘油三酯，具有降脂减肥的功效。空心菜中的叶绿素有“绿色精灵”之称，可洁齿防龋除口臭，健美皮肤。",
            },
        ],
        "imageContent":["https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
                        "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3637305469,1928156414&fm=26&gp=0.jpg",
                        "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3812919490,1110340930&fm=26&gp=0.jpg"],  # 合种租地图片详情
        "videos": "",  # 存放视频地址
        "status": "0",  # 状态
    },
{
        "land_id": "1",
        "land_title": "1号大棚",  # 标题
        "land_rules": "需要等待种植的种类成熟后方可寄出。", # 种植规则
        "imagesSlider": [
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3992045535,69144840&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3156874013,635811390&fm=26&gp=0.jpg"
        ], # 轮播图
        "defaultImgIndex": 0, # 默认图片索引（取轮播图）
        "land_stock": 27,  # 土地总块数
        "land_planted": 3,  # 土地已种植数
        "items":[  # 可选种植种类
            {
                "item_id": "1",
                "item_title": "菠菜",
                "item_cycle": 90,  # 生长周期
                "item_img": "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/"
                            "it/u=3637305469,1928156414&fm=26&gp=0.jpg",
                "item_price": 9.9,  # 价格
                "item_count": 5,  # 需达标数量
                "item_weight": 5, # 单份重量
                "item_introduce": "菠菜有“营养模范生”之称，它富含类胡萝卜素、维生素C、维生素K、矿物质（钙质、铁"
                                  "质等）、辅酶Q10等多种营养素。其可以经常用来烧汤，凉拌，单炒，和配荤菜合炒或垫盘。以色泽浓绿，根为红色，不着水，茎叶不老，无抽苔开花，不带黄烂叶者为佳"  # 描述
            },
            {
                "item_id": "1",
                "item_title": "空心菜",
                "item_cycle": 60,
                "item_img": "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3812919490,11103409"
                            "30&fm=26&gp=0.jpg",
                "item_price": 8.9,
                "item_count": 10,
                "item_weight": 5,
                "item_introduce": "空心菜是碱性食物，并含有钾、氯等调节水液平衡的元素，食后可降低肠道的酸度，预"
                                  "防肠道内的菌群失调，对防癌有益。所含的烟酸、维生素C等能降低胆固醇、甘油三酯，具有降脂减肥的功效。空心菜中的叶绿素有“绿色精灵”之称，可洁齿防龋除口臭，健美皮肤。",
            },
        ],
        "imageContent":["https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
                        "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3637305469,1928156414&fm=26&gp=0.jpg",
                        "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3812919490,1110340930&fm=26&gp=0.jpg"],  # 合种租地图片详情
        "videos": "",  # 存放视频地址
        "status": "0",  # 状态
    },
{
        "land_id": "1",
        "land_title": "1号大棚",  # 标题
        "land_rules": "需要等待种植的种类成熟后方可寄出。", # 种植规则
        "imagesSlider": [
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3992045535,69144840&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3156874013,635811390&fm=26&gp=0.jpg"
        ], # 轮播图
        "defaultImgIndex": 0, # 默认图片索引（取轮播图）
        "land_stock": 27,  # 土地总块数
        "land_planted": 3,  # 土地已种植数
        "items":[  # 可选种植种类
            {
                "item_id": "1",
                "item_title": "菠菜",
                "item_cycle": 90,  # 生长周期
                "item_img": "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/"
                            "it/u=3637305469,1928156414&fm=26&gp=0.jpg",
                "item_price": 9.9,  # 价格
                "item_count": 5,  # 需达标数量
                "item_weight": 5, # 单份重量
                "item_introduce": "菠菜有“营养模范生”之称，它富含类胡萝卜素、维生素C、维生素K、矿物质（钙质、铁"
                                  "质等）、辅酶Q10等多种营养素。其可以经常用来烧汤，凉拌，单炒，和配荤菜合炒或垫盘。以色泽浓绿，根为红色，不着水，茎叶不老，无抽苔开花，不带黄烂叶者为佳"  # 描述
            },
            {
                "item_id": "1",
                "item_title": "空心菜",
                "item_cycle": 60,
                "item_img": "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3812919490,11103409"
                            "30&fm=26&gp=0.jpg",
                "item_price": 8.9,
                "item_count": 10,
                "item_weight": 5,
                "item_introduce": "空心菜是碱性食物，并含有钾、氯等调节水液平衡的元素，食后可降低肠道的酸度，预"
                                  "防肠道内的菌群失调，对防癌有益。所含的烟酸、维生素C等能降低胆固醇、甘油三酯，具有降脂减肥的功效。空心菜中的叶绿素有“绿色精灵”之称，可洁齿防龋除口臭，健美皮肤。",
            },
        ],
        "imageContent":["https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
                        "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3637305469,1928156414&fm=26&gp=0.jpg",
                        "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3812919490,1110340930&fm=26&gp=0.jpg"],  # 合种租地图片详情
        "videos": "",  # 存放视频地址
        "status": "0",  # 状态
    },
{
        "land_id": "1",
        "land_title": "1号大棚",  # 标题
        "land_rules": "需要等待种植的种类成熟后方可寄出。", # 种植规则
        "imagesSlider": [
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3992045535,69144840&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3156874013,635811390&fm=26&gp=0.jpg"
        ], # 轮播图
        "defaultImgIndex": 0, # 默认图片索引（取轮播图）
        "land_stock": 27,  # 土地总块数
        "land_planted": 3,  # 土地已种植数
        "items":[  # 可选种植种类
            {
                "item_id": "1",
                "item_title": "菠菜",
                "item_cycle": 90,  # 生长周期
                "item_img": "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/"
                            "it/u=3637305469,1928156414&fm=26&gp=0.jpg",
                "item_price": 9.9,  # 价格
                "item_count": 5,  # 需达标数量
                "item_weight": 5, # 单份重量
                "item_introduce": "菠菜有“营养模范生”之称，它富含类胡萝卜素、维生素C、维生素K、矿物质（钙质、铁"
                                  "质等）、辅酶Q10等多种营养素。其可以经常用来烧汤，凉拌，单炒，和配荤菜合炒或垫盘。以色泽浓绿，根为红色，不着水，茎叶不老，无抽苔开花，不带黄烂叶者为佳"  # 描述
            },
            {
                "item_id": "1",
                "item_title": "空心菜",
                "item_cycle": 60,
                "item_img": "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3812919490,11103409"
                            "30&fm=26&gp=0.jpg",
                "item_price": 8.9,
                "item_count": 10,
                "item_weight": 5,
                "item_introduce": "空心菜是碱性食物，并含有钾、氯等调节水液平衡的元素，食后可降低肠道的酸度，预"
                                  "防肠道内的菌群失调，对防癌有益。所含的烟酸、维生素C等能降低胆固醇、甘油三酯，具有降脂减肥的功效。空心菜中的叶绿素有“绿色精灵”之称，可洁齿防龋除口臭，健美皮肤。",
            },
        ],
        "imageContent":["https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
                        "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3637305469,1928156414&fm=26&gp=0.jpg",
                        "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3812919490,1110340930&fm=26&gp=0.jpg"],  # 合种租地图片详情
        "videos": "",  # 存放视频地址
        "status": "0",  # 状态
    },
{
        "land_id": 19,
        "land_title": "1号大棚",  # 标题
        "land_rules": "需要等待种植的种类成熟后方可寄出。", # 种植规则
        "imagesSlider": [
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3992045535,69144840&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3156874013,635811390&fm=26&gp=0.jpg"
        ], # 轮播图
        "defaultImgIndex": 0, # 默认图片索引（取轮播图）
        "land_stock": 27,  # 土地总块数
        "land_planted": 3,  # 土地已种植数
        "items":[
        ],
        "imageContent":["https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
                        "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3637305469,1928156414&fm=26&gp=0.jpg",
                        "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3812919490,1110340930&fm=26&gp=0.jpg"],  # 合种租地图片详情
        "vedios": "",  # 存放视频地址
        "status": 1,  # 状态
    },
]

initLandItemData = {
        "land_id": 0,
        "land_title": "",  # 标题
        "land_rules": "", # 种植规则
        "imagesSlider": [
            "请点击插入图片",
            "请点击插入图片",
            "请点击插入图片"
        ], # 轮播图
        "defaultImgIndex": 0, # 默认图片索引（取轮播图）
        "land_stock": 0,  # 土地总块数
        "land_planted": 0,  # 土地已种植数
        "items":[  # 可选种植种类
        ],
        "imageContent":["请点击插入图片",
                        "请点击插入图片",
                        "请点击插入图片"],  # 合种租地图片详情
        "vedios": "",  # 存放视频地址
        "status": 1,  # 状态
}

initLandPlantData = {
                "item_id": 0,
                "item_title": "",
                "item_cycle": 0,  # 生长周期
                "item_img": "请点击插入图片",
                "item_price": 0,  # 价格
                "item_count": 0,  # 需达标数量
                "item_weight": 0, # 单份重量
                "item_introduce": "",  # 描述
                "status": 0,
                "remark": ""
}

class LandItem(shopItem):
    def __init__(self, parent=None):
        super(LandItem, self).__init__(parent=parent, labelcount=2, displaytype=0,
                                       labelalign=Qt.AlignLeft, pic_label_space=0)
        self.setFixedSize(390, 270)
        self._setPicSize((400, 200))
        sd = QGraphicsDropShadowEffect()
        sd.setColor(Qt.gray)
        sd.setBlurRadius(8)
        self.setGraphicsEffect(sd)

    def set_data(self, data):
        self._data = data

    def updateData(self, data):
        self._data = data
        # 显示图片

        # 显示标题
        font = QFont()
        font.setBold(True)
        font.setPixelSize(14)
        font.setFamily("黑体")
        self._descLbList[0].setFont(font)
        self._descLbList[0].setText(data["land_title"])

        # 显示可种植菜品
        font.setPixelSize(13)
        font.setBold(False)
        font.setFamily("SimSun")
        font.setItalic(True)
        text = "可种:"
        for each in range(data["items"].__len__()):
            text += data["items"][each]["item_title"]
            if each != (data["items"].__len__() - 1):
                text += "、"
        self._descLbList[1].setText(text)

        url = data["imagesSlider"][data["defaultImgIndex"]]
        # ret = self._displayImg(url, self._picLb)
        # if ret is not None:
        #     data["imagesSlider"][data["defaultImgIndex"]] = ret
        self.q_request(url)

    def getSize(self):
        return [390, 270]

class landPlantItem(shopItem):
    def __init__(self, parent=None):
        super(landPlantItem, self).__init__(parent=parent, labelcount=5, displaytype=1,
                                            labelalign=Qt.AlignLeft, pic_label_space=0)
        self.setFixedSize(300, 100)
        self._setPicSize((100, 100))

        sd = QGraphicsDropShadowEffect()
        sd.setColor(Qt.gray)
        sd.setBlurRadius(8)
        self.setGraphicsEffect(sd)

    def updateData(self, data):
        self._data = data
        # 显示图片
        url = data["item_img"]

        ret = self._displayImg(url, self._picLb)
        if ret is not None:
            data["item_img"] = ret
        #self.q_request(url)
        # 显示标题
        font = QFont()
        font.setBold(True)
        font.setPixelSize(14)
        font.setFamily("黑体")
        self._descLbList[0].setFont(font)
        self._descLbList[0].setText(data["item_title"])

        self._descLbList[1].setStyleSheet("color: red")
        font.setPixelSize(20)
        self._descLbList[1].setFont(font)
        self._descLbList[1].setText("¥" + str(data["item_price"]))

        # 显示可种植菜品
        font.setPixelSize(13)
        font.setBold(False)
        font.setFamily("SimSun")
        font.setItalic(True)
        self._descLbList[2].setFont(font)
        self._descLbList[2].setText("周期:" + str(data["item_cycle"]))

        self._descLbList[3].setFont(font)
        self._descLbList[3].setText("需达标数量:" + str(data["item_count"]))

        self._descLbList[4].setFont(font)
        self._descLbList[4].setText("单份重量:" + str(data["item_weight"]))

    def getSize(self):
        return [300, 100]

class LandPlantItemEditWidget(EditWidget):
    def __init__(self, parent=None):
        super(LandPlantItemEditWidget, self).__init__(parent=parent, has_status=False)
        self._slideWidget = slideShowWidget(pic_count=1)
        self._landPlantMsgEditWidget = msgEditWidget(rowcount=5)

        self._landPlantMsgEditWidget.setLabelsText(["标题:", "价格:", "生长周期:", "需达标数量:", "单份重量:"])
        self._landPlantMsgEditWidget.setLineEditNumberLimit(1, (0, 100000000), float)
        self._landPlantMsgEditWidget.setLineEditNumberLimit(2, (0, 100000000), float)
        self._landPlantMsgEditWidget.setLineEditNumberLimit(3, (0, 100000000))
        self._landPlantMsgEditWidget.setLineEditNumberLimit(4, (0, 100000000), float)
        font = QFont()
        font.setBold(True)
        font.setFamily("SimSun")
        font.setPixelSize(17)
        self._landPlantMsgEditWidget.setLabelFont(font)

        # 介绍
        self._introduceLb = QLabel()
        self._introduceEdit = QPlainTextEdit()
        self._introduceEdit.setMinimumSize(700, 50)
        self._introduceEdit.setFont(font)
        self._introduceLb.setFont(font)
        self._introduceLb.setText("介绍:")
        self._introduceLb.setAlignment(Qt.AlignCenter)
        # self._introduceLb.setStyleSheet("background-color: qlineargradient(x0:0, x1:1, stop: 0 #1fa2ff, "
        #                                       "stop: 0.5 #12d8fa, stop: 1 #a6ffcb);")
        self._introduceLb.setObjectName("titleLabel")
        #self._introduceLb.setFixedSize(1100, 27)
        self._introduceLb.setProperty("class", "titleLabel")
        #self.setStyleSheet("background-color:#00FFFF")
        self._initLayout()
        self._unShelveBtn.hide()

    def _newItem(self):
        return landPlantItem()

    def _initLayout(self):
        # 整体界面布局
        glayout = QGridLayout()
        glayout.addWidget(self._slideWidget, 0, 0, 1, 1)
        glayout.addWidget(self._landPlantMsgEditWidget, 0, 1, 1, 1)
        glayout.addWidget(self._btnWidget, 0, 2, 1, 1)
        glayout.addWidget(self._introduceLb, 1, 0, 1, 3, Qt.AlignCenter)
        glayout.addWidget(self._introduceEdit, 2, 0, 1, 3)
        # glayout.setColumnStretch(0, 1)
        # glayout.setColumnStretch(1, 1)
        glayout.setContentsMargins(0, 20, 0, 0)
        self._mainWidget.setLayout(glayout)
        self._mainWidget.resize(1100, 600)

    def updateData(self, data, isinit=False):
        self._isinit = isinit
        self._data = data
        if not isinit:
            self._goodsItem = self.sender()
        else:
            self._goodsItem = None

        msgLineEdit = self._landPlantMsgEditWidget.getWidget()
        msgLineEdit[0][1].setText(data["item_title"])
        msgLineEdit[1][1].setText(str(data["item_price"]))
        msgLineEdit[2][1].setText(str(data["item_cycle"]))
        msgLineEdit[3][1].setText(str(data["item_count"]))
        msgLineEdit[4][1].setText(str(data["item_weight"]))

        self._slideWidget.showPic(data["item_img"])
        ret = list()
        ret.append(data["item_img"])
        self._slideWidget.setPicData(ret)
        self._introduceEdit.setPlainText(data["item_introduce"])

    def getEditedData(self):
        msgLineEdit = self._landPlantMsgEditWidget.getWidget()
        self._data["item_title"] = msgLineEdit[0][1].text()
        self._data["item_price"] = float(msgLineEdit[1][1].text())
        self._data["item_cycle"] = float(msgLineEdit[2][1].text())
        self._data["item_count"] = int(msgLineEdit[3][1].text())
        self._data["item_weight"] = float(msgLineEdit[4][1].text())
        self._data["item_img"] = self._slideWidget.getPic()[0]
        self._data["item_introduce"] = self._introduceEdit.toPlainText()

        return self._data

class LandItemEditWidget(EditWidget):
    def __init__(self, parent=None):
        super(LandItemEditWidget, self).__init__(parent=parent)
        self._slideWidget = slideShowWidget()
        self._landMsgEditWidget = msgEditWidget(rowcount=3)
        self._initEditWidget()

        self._detailsWidget = QWidget()
        self._detailsWidget.setMinimumSize(1300, 1800)
        self._detailsPicLb = list()
        for index in range(3):
            self._detailsPicLb.append(picEditableLabel(index))
            self._detailsPicLb[index].picLbClicked.connect(self._uplaodPic)
        glayout = QGridLayout()
        for each in range(self._detailsPicLb.__len__()):
            self._detailsPicLb[each].setMinimumSize(1000, 600)
            glayout.addWidget(self._detailsPicLb[each], each, 0, Qt.AlignCenter)
        glayout.setSpacing(0)
        self._detailsWidget.setLayout(glayout)

        # 种植规则
        self._rulesLb = QLabel()
        self._rulesPlainEdit = QPlainTextEdit()
        self._rulesPlainEdit.setMinimumSize(800, 50)
        font = QFont()
        font.setBold(True)
        font.setFamily("SimSun")
        font.setPixelSize(17)
        self._rulesPlainEdit.setFont(font)
        self._rulesLb.setFont(font)
        self._rulesLb.setText("种植规则:")
        self._rulesLb.setAlignment(Qt.AlignCenter)
        # self._rulesLb.setStyleSheet("background-color: qlineargradient(x0:0, x1:1, stop: 0 #1fa2ff, "
        #                                 "stop: 0.5 #12d8fa, stop: 1 #a6ffcb);")
        # self._rulesLb.setFixedSize(1300, 27)
        self._rulesLb.setProperty("class", "titleLabel")

        self._plantLb = QLabel()
        self._plantLb.setText("可种产品:")
        self._plantLb.setFont(font)
        self._plantLb.setAlignment(Qt.AlignCenter)
        self._plantLb.setAlignment(Qt.AlignCenter)
        # self._plantLb.setStyleSheet("background-color: qlineargradient(x0:0, x1:1, stop: 0 #1fa2ff, "
        #                             "stop: 0.5 #12d8fa, stop: 1 #a6ffcb);")
        # self._plantLb.setFixedSize(1300, 27)
        self._plantLb.setProperty("class", "titleLabel")

        # 可种植的产品
        self._landPlantItemShowWidget = ItemDisplayWidget(item=landPlantItem,
                                                          data=[], init_data=initLandPlantData,
                                                          edit_widget=LandPlantItemEditWidget,
                                                          col_count=3)

        self._initLayout()
        self._unShelveBtn.hide()

    def _initEditWidget(self):
        self._landMsgEditWidget.setLabelsText(["标题:", "土地总块数:", "土地已种植数:"])
        self._landMsgEditWidget.setLineEditNumberLimit(1, (0, 100000000))
        self._landMsgEditWidget.setLineEditNumberLimit(2, (0, 100000000))
        font = QFont()
        font.setBold(True)
        font.setFamily("SimSun")
        font.setPixelSize(17)
        self._landMsgEditWidget.setLabelFont(font)

    def _newItem(self):
        return LandItem()

    def updateData(self, data, isinit=False):
        self._isinit = isinit
        self._data = data

        msgLineEdit = self._landMsgEditWidget.getWidget()
        msgLineEdit[0][1].setText(data["land_title"])
        msgLineEdit[1][1].setText(str(data["land_stock"]))
        msgLineEdit[2][1].setText(str(data["land_planted"]))

        self._slideWidget.showPic(data["imagesSlider"][0])
        self._slideWidget.setPicData(data["imagesSlider"])

        for each in range(data["imageContent"].__len__()):
            ret = self._displayimg(data["imageContent"][self._detailsPicLb[each].index()], self._detailsPicLb[each])
            if ret is not None:
                data["imageContent"][self._detailsPicLb[each].index()] = ret

        self._rulesPlainEdit.setPlainText(data["land_rules"])
        self._landPlantItemShowWidget.disPlayGoodsItem(data["items"], refresh=True, data_refresh=True)
        if not isinit:
            self._goodsItem = self.sender()
        else:
            self._goodsItem = None

    def getEditedData(self):
        msgLineEdit = self._landMsgEditWidget.getWidget()
        self._data["land_title"] = msgLineEdit[0][1].text()
        self._data["land_stock"] = int(msgLineEdit[1][1].text())
        self._data["land_planted"] = int(msgLineEdit[2][1].text())
        self._data["imagesSlider"] = self._slideWidget.getPic()
        self._data["land_rules"] = self._rulesPlainEdit.toPlainText()
        self._data["items"] = self._landPlantItemShowWidget.getData()

        return self._data

    def _initLayout(self):
        # 整体界面布局
        glayout = QGridLayout()
        glayout.addWidget(self._slideWidget, 0, 0, 1, 1)
        glayout.addWidget(self._landMsgEditWidget, 0, 1, 1, 1)
        glayout.addWidget(self._btnWidget, 0, 2, 1, 1)
        glayout.addWidget(self._rulesLb, 1, 0, 1, 3, Qt.AlignCenter)
        glayout.addWidget(self._rulesPlainEdit, 2, 0, 1, 3)
        glayout.addWidget(self._plantLb, 3, 0, 1, 3, Qt.AlignCenter)
        glayout.addWidget(self._landPlantItemShowWidget, 4, 0, 1, 3)
        glayout.addWidget(self._detailsWidget, 5, 0, 1, 3)
        glayout.setContentsMargins(0, 20, 0, 0)
        self._mainWidget.setLayout(glayout)
        self._mainWidget.resize(1200, 3000)

    # 上传轮播图或图片详情图片
    def _uplaodPic(self, mode):
        fd = FileDialog(QFileDialog.AcceptOpen, "选择图片")
        path = fd.getSelectFilePath()
        if path is not None:
            img = cv2.imdecode(np.fromfile(path, dtype=np.uint8), -1)
            # ---------------------------------压缩图片--------------#
            # width = img.shape[1]
            # height = img.shape[0]
            # width_new = 680
            # height_new = 420
            # # 判断图片的长宽比率
            # if width / height >= width_new / height_new:
            #     img_new = cv2.resize(img, (width_new, int(height * width_new / width)))
            # else:
            #     img_new = cv2.resize(img, (int(width * height_new / height), height_new))
            # ----------------------------------------------------------
            img_new = img
            cv2.imwrite('./temp/temp.jpg', img_new)
            with open('./temp/temp.jpg', "rb") as file:
                image_byte = b64encode(file.read())
            base64_string = image_byte.decode('utf-8')
            if mode == -1:
                index = self._currentSlideBtn.index()
                self._data["imagesSlider"][index] = base64_string
                self._updateSlidePicFromFile(index)
            else:
                self._data["imageContent"][mode] = base64_string
                self._updateDedetailsPic(self._detailsPicLb[mode])

    def _updateDedetailsPic(self, label):
        ret = self._displayimg(self._data["imageContent"][label.index()], label)
        if ret is not None:
            self._data["imageContent"][label.index()] = ret

    def _displayimg(self, url, label):
        pix = QPixmap()
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        if url.startswith("http"):
            QApplication.processEvents()
            response = requests.get(url)
            pix.loadFromData(response.content)
            pix = pix.scaled(label.width(), label.height())
            label.setStyleSheet("border:none")
            label.setPixmap(pix)
            image_byte = b64encode(response.content)
            base64_string = image_byte.decode('utf-8')
            QApplication.restoreOverrideCursor()
            return base64_string
        elif url == "请点击插入图片":
            label.setText(url)
            label.setStyleSheet("background-color:gray;border: 1px solid black;")
        else:
            url = url.encode("utf-8")
            image_data = b64decode(url)
            pix.loadFromData(image_data)
            pix = pix.scaled(label.width(), label.height())
            label.setStyleSheet("border:none")
            label.setPixmap(pix)
        QApplication.restoreOverrideCursor()
        return None

class LandWidget(ItemDisplayWidget):
    def __init__(self, parent=None):
        super(LandWidget, self).__init__(item=LandItem, data=[], init_data=initLandItemData,
                                         edit_widget=LandItemEditWidget, col_count=3,
                                         parent=parent, desc="租地上架管理")
        self._handle = LeaseLandHandle()
        self._current_item_ids = list()

    def _new_image_name(self):
        img_name = str(time.time()).replace('.', '') + '.jpg'
        return img_name

    def _get_land_items_id(self, data):
        ret = list()
        for each in data:
            ret.append(each["item_id"])
        return ret

    def _changeWidget(self, data):
        self.sender().setDataIndex(self._data.index(data))
        self.setCurrentIndex(1)
        self._current_item_ids = self._get_land_items_id(data["items"])
        self._editWidget.updateData(copy.deepcopy(data))

    def _get_imgs(self, img_list):
        ret = list()
        for each in img_list:
            if each.startswith("http"):
                try:
                    file = requests.get(each)
                    img = cv2.imdecode(np.fromstring(file.content, np.uint8), 1)
                    imgname = './temp/' + self._new_image_name()
                    ret.append(imgname)
                    cv2.imwrite(imgname, img)
                except Exception as e:
                    print(e)
                    return False, None
            elif each == "请点击插入图片":
                pass
            else:
                url = each.encode("utf-8")
                image_data = b64decode(url)
                img = cv2.imdecode(np.fromstring(image_data, np.uint8), 1)
                imgname = './temp/' + self._new_image_name()
                ret.append(imgname)
                cv2.imwrite(imgname, img, [int(cv2.IMWRITE_JPEG_QUALITY), 40])

        return True, ret

    def _compare_item_ids(self, data):
        temp = self._get_land_items_id(data)

        add_list = [i for i in range(temp.__len__()) if temp[i] == 0]
        del_list = [i for i in self._current_item_ids if i not in temp]
        update_list = [i for i in temp if i in self._current_item_ids]

        for each in range(update_list.__len__()):
            update_list[each] = (temp.index(update_list[each]), update_list[each])

        return add_list, del_list, update_list

    def _get_land_post_data(self, post_data):
        post_data["create_by"] = "yixianshenji"
        post_data["update_by"] = "yixianshenji"
        post_data["status"] = 0
        post_data["items"] = ""
        state, ret = self._get_imgs(post_data["imagesSlider"])
        state1, ret1 = self._get_imgs(post_data["imageContent"])
        if state and state1 and ret.__len__() > 0 and ret1.__len__() > 0:
            post_data["imagesSlider"] = ret
            post_data["imageContent"] = ret1
            return True, post_data
        else:
            return False, None

    def _update_plant(self, items, lnad_id, data):
        if items.__len__() > 0:
            for each in range(items.__len__()):
                items[each]["land_id"] = lnad_id
                state_item, ret_item = self._get_imgs([items[each]["item_img"]])

                if state_item and ret_item.__len__() > 0:
                    items[each]["item_img"] = ret_item[0]
                    items[each]["create_by"] = "yixianshenji"
                    items[each]["update_by"] = "yixianshenji"
                    state_res, res = self._handle.updatePlant(items[each])
                    print(res)
                    if state_res:
                        data["items"][each]["item_id"] = res["item_id"]
                    else:
                        WarningMessageBox("上架失败, 服务器异常, 请重启程序").exec()
                        return False

        return True

    def _onStatusChange(self, status):
        self._editWidget.setSalesStatus(status[0])
        data = self._editWidget.getEditedData()
        post_data = copy.deepcopy(data)
        if status[0]:
            if status[1]:
                items = post_data["items"]
                state, post_data = self._get_land_post_data(post_data)
                if state:
                    state, res = self._handle.updateLand(post_data)
                    print(res)
                    if state:
                        data["land_id"] = res.get("land_id")

                        state = self._update_plant(items, res.get("land_id"), data)
                        if not state:
                            return
                    else:
                        WarningMessageBox("上架失败, 服务器异常").exec()
                        return
                else:
                    WarningMessageBox("上架失败, 图片不能为空，或服务器异常").exec()
                    return
            else:
                items = post_data["items"]
                state, post_data = self._get_land_post_data(post_data)
                if state:
                    state, res = self._handle.updateLand(post_data)
                    print(res)
                    if state:
                        data["land_id"] = res.get("land_id")
                        add_list, del_list, update_list = self._compare_item_ids(items)
                        add_items = list()
                        for each in add_list:
                            add_items.append(items[each])

                        state = self._update_plant(add_items, res.get("land_id"), data)

                        if not state:
                            return

                        for each in del_list:
                            state, res = self._handle.del_plant(res.get("land_id"), each)
                            if not state:
                                WarningMessageBox("更新失败, 服务器异常").exec()
                                return
                        update_items = list()
                        for each in update_list:
                            update_items.append(items[each[0]])

                        state = self._update_plant(update_items, res.get("land_id"), data)
                        if not state:
                            return
                    else:
                        WarningMessageBox("上架失败, 服务器异常").exec()
                        return
                else:
                    WarningMessageBox("上架失败, 图片不能为空，或服务器异常").exec()
                    return

        shutil.rmtree('./temp')
        os.mkdir('./temp')

        ret = self._editWidget.updateGoodsItem()

        if ret is not None:
            self._data.append(data)
            print(data["land_id"])

            ret.shopItemClicked.connect(self._changeWidget)  # gai
            self._goodsList.append(ret)
            self._glayout.addWidget(ret, (self._goodsList.__len__()-1)//self._colCount+1,
                                    (self._goodsList.__len__()-1)%self._colCount,
                                    1, 1, Qt.AlignTop | Qt.AlignLeft)
            self._goodsWidget.resize(self._colCount * self._itemSize[0] + 80,
                                     ((self._goodsList.__len__() - 1) // self._colCount + 1)
                                     * (self._itemSize[1] + 15) + 30 + self._addGoodsItemBtn.height())
        else:
            item = self._editWidget.currentEditItem()
            self._data[item.dataIndex()] = data

        self.setCurrentIndex(0)

    def _onDelete(self, item):
        if item[0] is None:
            self.setCurrentIndex(0)
        else:
            item_data = item[0].getData()
            land_id = item_data["land_id"]
            state, res = self._handle.del_land(land_id)
            if not state:
                WarningMessageBox("删除失败, 服务器异常").exec()
                return

            self.setCurrentIndex(0)
            # 去除界面布局
            for each in self._goodsList:
                self._glayout.removeWidget(each)

            # 删除对应商品
            index = item[0].dataIndex()
            del self._data[index]
            goodsindex = self._goodsList.index(item[0])
            item[0].setParent(None)
            item[0].deleteLater()
            del self._goodsList[goodsindex]

            # 重新布局
            self._reshow()

def main():
    app = QApplication(sys.argv)

    ui = ItemDisplayWidget(item=LandItem, data=landList, init_data=initLandItemData,
                           edit_widget=LandItemEditWidget, col_count=2)
    # ui = landPlantItem()
    # ui.updateData(landList[0]["items"][0])
    ui.show()
    # ui.show()
    # ui.updateData(landList[0])

    sys.exit(app.exec())

if __name__ == "__main__":
    main()

